import axios from 'axios'
import NProgress from 'nprogress'
import { Message } from 'element-ui'
import { CONSTANT_OBJ } from '@/utils/constant'
import router from '@/router'
import { getCookie, delCookie } from '@/utils/util'
import { unifiedLogin } from '@/utils/auth'
NProgress.configure({ showSpinner: false })

let baseURL
// let locationHref = `http://${window.location.host}` // 浏览器当前的url ip
let locationHref = `http://${window.location.host}`

  // baseURL = CONSTANT_OBJ.URL + CONSTANT_OBJ.PREFIX  // dev
baseURL = locationHref + CONSTANT_OBJ.PREFIX // 打包

const service = axios.create({
  baseURL,
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout 30s
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['Accept'] = 'application/json, application/octet-stream'
    config.headers['Content-Type'] = 'application/json'
    // config.headers['X-access-token'] = auth.getUser().token || null
    config.headers['X-access-token'] = getCookie('usertoken') || null
    // config.headers['X-access-id'] = auth.getUser().userId || null
    config.headers['systemFlag'] = 5
    // config.headers['productCode'] = 'bps'
    NProgress.start()
    return config
  },
  error => {
    // do something with request error
    //  console.log(error) // for debug
    this.$message.warnng(error.message)
    return Promise.reject(error)
  })

// response interceptor
service.interceptors.response.use(
  response => {
    const status = response.status
    const res = response.data
    const token = getCookie('usertoken')
    NProgress.done()
    console.log('router.currentRoute', router.currentRoute)
    if (!token) {
      if (router.currentRoute.name !== 'LOGIN') {
        Message.error({ showClose: true, message: `用户已登出，请重新登录` })
        unifiedLogin()
      }
    }
    console.log('responseMsg', response.data.responseMsg)
    if (response.data.responseMsg === '当前用户未登陆') {
      unifiedLogin()
    }
    if (response.data.responseMsg === '登录已过期，请重新登录') {
      unifiedLogin()
    }
    if (res && status === 200) {
      const { code, message, responseCode, responseMsg } = res
      let resCode = code || responseCode
      let resMessage = message || responseMsg
      if (resCode !== CONSTANT_OBJ.RES_SUCCESS) {
        if (resCode === 9017) {
          delCookie('usertoken')
          delCookie('userName')
          delCookie('userId')
          delCookie('isFirstLogin')
          unifiedLogin()
        } else if (resMessage) {
          Message({
            // message: `${resMessage}(${resCode})`,
            message: `${resMessage}`,
            type: 'error'
          })
        } else if (response.headers['content-type'] === 'application/octet-steam') {
          return res
        } else {
          Message({
            message: `程序异常！！！`,
            type: 'error'
          })
          throw new Error('程序异常了！！！')
        }
      }
      return res
    }
  },
  error => {
    const errorRes = error.response
    if (errorRes) {
      const { status, data: { message } } = errorRes
      switch (status) {
        case 404:
          Message.error({ showClose: true, message: message || `您的请求不存在！！！(${status})` })
          break
        case 502:
          Message.error({ showClose: true, message: message || `服务器异常了！！！(${status})` })
          break
        case 400:
          Message.error({ showClose: true, message: message || `参数错误了！！！(${status})` })
          break
        case 401:
          unifiedLogin()
          break
        case 403:
          Message.error({ showClose: true, message: `您暂无权限访问该功能,请联系管理员分配权限` })
          break
        default:
          Message.error({ showClose: true, message: message || `网络异常了！！！(${status})` })
      }
    } else {
      Message.error({ showClose: true, message: error.message || '服务器异常了！！！' })
    }
    NProgress.done()
    return Promise.reject(error)
  }
)

export default service
